"use strict";

var DEFAULT_QUALITY = 0.75;	//QUALITY 质量

/**
 * src 转 webp格式
 */
export function srcToWebP(src, {
	quality: quality,
	width: width,
	height: height
} = {}) {
	return new Promise(function(resolve, reject) {
		var canvas = document.createElement('canvas');
		var context = canvas.getContext('2d');
		var image = new Image();
		image.src = src;
		image.crossOrigin = 'anonymous';
		image.onload = function(e) {
			canvas.width = width || image.width;
			canvas.height = height || image.height;
			// @ts-ignore
			URL.revokeObjectURL(e.target.src);
			// @ts-ignore
			context.drawImage(e.target, 0, 0, canvas.width, canvas.height);
			canvas.toBlob(function(data) {
				resolve(data);
			}, 'image/webp', quality || DEFAULT_QUALITY);
		};
		image.onerror = function(e) {
			return reject(e);
		};
	});
}
// blob 转 webp格式
export function blobToWebP(data, {
	quality: quality,
	width: width,
	height: height
} = {}) {
	return srcToWebP(URL.createObjectURL(data), {
		quality: quality,
		width: width,
		height: height
	});
}

export function arrayBufferToWebP(data, {
	quality: quality,
	width: width,
	height: height
} = {}) {
	return blobToWebP(new Blob([data]), {
		quality: quality,
		width: width,
		height: height
	});
}
// 格式互转 默认是webp
export function srcToType(src, type = 'image/webp',{
	quality: quality,
	width: width,
	height: height
} = {}) {
	return new Promise(function(resolve, reject) {
		var canvas = document.createElement('canvas');
		var context = canvas.getContext('2d');
		var image = new Image();
		image.src = src;
		image.crossOrigin = 'anonymous';
		image.onload = function(e) {
			canvas.width = width || image.width;
			canvas.height = height || image.height;
			// @ts-ignore
			URL.revokeObjectURL(e.target.src);
			// @ts-ignore
			context.drawImage(e.target, 0, 0, canvas.width, canvas.height);
			canvas.toBlob(function(data) {
				resolve(data);
			}, type, quality || DEFAULT_QUALITY);
		};
		image.onerror = function(e) {
			return reject(e);
		};
	});
}
export async function downImg(url, {
	quality: quality,
	width: width,
	height: height
} = {}) {
	let b = await srcToType(url, 'image/png',{
		quality: quality,
		width: width,
		height: height
	});
	let e = new MouseEvent('click');
	let link = URL.createObjectURL(b);
	const a = document.createElement('a');
	a.download = 'down load'
	a.href = link;
	a.dispatchEvent(e);
}

export default { downImg ,blobToWebP,arrayBufferToWebP,srcToWebP,srcToType}